package me.jiatao.jetpack.viewmodel;

import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.MutableLiveData;
import android.arch.lifecycle.ViewModel;
import android.os.Handler;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

import me.jiatao.jetpack.databinding.User;

/**
 * Created by JiaTao on 2018/10/8.
 * Email: 535318720@qq.com
 * Version: 1.0
 * Description:
 */
public class MyViewModel extends ViewModel {
    private MutableLiveData<List<User>> usersLiveData;

    public LiveData<List<User>> getUsers() {
        if (usersLiveData == null) {
            usersLiveData = new MutableLiveData<>();
            loadUsers();
        }
        return usersLiveData;
    }

    private void loadUsers() {
        // 异步调用获取用户列表
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                List<User> listUsers = new ArrayList<>();
                listUsers.add(new User("tao", "jia"));
                listUsers.add(new User("tao1", "jia1"));
                listUsers.add(new User("tao2", "jia2"));
                listUsers.add(new User("tao3", "jia3"));
                listUsers.add(new User("tao4", "jia4"));

                usersLiveData.setValue(listUsers);
            }
        }, 3000);
    }

    @Override
    protected void onCleared() {
        super.onCleared();
        Log.i("********","MyViewModel-------->onCleared");
        List<User> users = usersLiveData.getValue();
        if (users!=null){
            usersLiveData.getValue().clear();
            usersLiveData.setValue(null);
        }
    }
}
